package data;

import java.util.ArrayList;
import java.util.Collections;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;

import models.CooperationModel;

import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyOpts;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;

public class CooperationData {
	
	private Objectify ofy;

	private Cache cache = null;

	private String prefix = "cooperation_";

	public CooperationData() {
		try {
			ObjectifyService.register(CooperationModel.class);
		} catch (Exception e) {
			// e.printStackTrace();
		}

		try {
			cache = CacheManager.getInstance().getCacheFactory()
					.createCache(Collections.emptyMap());
		} catch (CacheException e) {
			// e.printStackTrace();
		}

		ObjectifyOpts opts = new ObjectifyOpts().setSessionCache(true);
		ofy = ObjectifyService.begin(opts);
	}

	public void insert(CooperationModel cooperation) {
		if (cache != null) {
			cache.put(prefix + cooperation.getId(), cooperation);
		}
		ofy.put(cooperation);
	}

	public void delete(CooperationModel cooperation) {
		if (cache != null && cache.containsKey(prefix + cooperation.getId())) {
			cache.remove(prefix + cooperation.getId());
		}

		ofy.delete(cooperation);
	}
}
